﻿using System;
using System.Collections.Generic;
using Pixels.Logic;

namespace Pixels.Logic.Generators
{
    class WorldGenerator
    {
        public Map generateRandomMap(int seed, int w, int h) {

            var m = new Map();
            m.create(w, h);

            foreach (var tile in m) {
                // empty rocks map
                tile.changeType(TerrainType.rocks);

                //tile.visibility = Visibility.visible;//DEBUG

                //Procedural map generation - WIP
                int tileHash;

                //TRY 01 - Random:
                //tileHash = Ur.Random.QuickRnd.range(1, 9);

                //TRY 02 Original:
                tileHash = (seed * tile.x + tile.x * tile.y) % 9;
                //TRY 02b
                tileHash = (seed + seed * tile.x ^ 2 + tile.y ^ seed) % 25;


                //TRY 03 Internet sucks:
                /*
                System.Security.Cryptography.MD5 hasher = System.Security.Cryptography.MD5.Create();
                string valuesAsString = string.Join(",", tileHash);
                var hash = hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(valuesAsString));
                int hashAsInt = BitConverter.ToInt32(hash, 0);
                tileHash = Math.Abs(hashAsInt % 9);
                */

                //TRY 04 Internet sucks 2:
                //tileHash = Math.Abs(441 * tile.x - 311 * tile.y) % 9;

                //TRY 05 Internet sucks 3:
                /*
                //int hash = 17;
                for (int i = 0, l = w; i < l; ++i)
                {
                    hash = hash * 31 + tile.x;
                    hash = hash * 31 + tile.y;
                }
                //return hash;
                hash = hash % 9;
                */




                switch (tileHash)
                {
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                        tile.changeType(TerrainType.rocks);
                        break;
                    case 6:
                    case 7:
                        tile.changeType(TerrainType.crystals);
                        break;
                    case 8:
                        tile.changeType(TerrainType.fertile);
                        break;
                    //case 9:
                    default:
                        tile.changeType(TerrainType.rocks);
                        break;
                        //return null;
                }

                //if ((tile.x == 10) && (tile.y == 10)) tile.discovered = true;//DEBUG
                
            }

            //m[0, 0].visibility = Visibility.visible;//DEBUG

            return m;

        }
    }
}
